package com.meme.editor.property.control;

import org.apache.log4j.Logger;

import com.meme.editor.property.Property;
import com.meme.editor.property.PropertyControl;

import javax.swing.JComponent;
import javax.swing.JComboBox;
import java.awt.event.ActionListener;

import java.util.Vector;
import java.util.List;

public class SelectListPropertyControl extends PropertyControl implements ActionListener
{
	static Logger logger = Logger.getLogger (SelectListPropertyControl.class);
	
	JComboBox mComboBox;
	
	public SelectListPropertyControl ()
	{
	}
	
	@Override
	public void enableEvents ()
	{
		mComboBox.addActionListener (this);
	}
	
	@Override
	public void disableEvents ()
	{
		mComboBox.removeActionListener (this);
	}
	
	@Override
	public void updateFromValue (Object[] controlParams) 
	{
		logger.assertLog (controlParams.length == 2, "the number of params is not correct.");
		logger.assertLog (controlParams[0] instanceof Integer, "the 1st param must be an int array.");
		logger.assertLog (controlParams[1] instanceof List, "the 2nd param must be a Vector.");
		
		JComboBox combobox = (JComboBox) getComponent ();
		combobox.removeAllItems();
		
		for ( Object o : (List) controlParams[1] )
			combobox.addItem (o);
		
		combobox.setSelectedIndex ( ( (Integer) controlParams[0] ).intValue () );
	}
	
	@Override
	public void updateFromValue ()
	{
		logger.error ("Shouldn't call this.");
	}
	
	@Override
	public Object[] makeDataForValue ()
	{
		return new Object[] 
		    {
				( (JComboBox)getComponent () ).getSelectedIndex ()
		    };
		//return ( (JList)getComponent () ).getSelectedValues();
	}
	
//	@Override
//	public void setEditable (boolean bEditable)
//	{		
//		( (JComboBox)getComponent () ).setEnabled (bEditable);
//	}
	
	@Override
	public JComponent getComponent ()
	{
		if (mComboBox == null)
		{
			mComboBox = new JComboBox ();
			mComboBox.setEditable (false);
			mComboBox.addActionListener (this);
		}
		
		mComboBox.setEditable ( isEditable ());
		
		return mComboBox;
	}

	@Override
	public void disposeComponent ()
	{
		if( mComboBox!= null )
		{
			mComboBox.removeActionListener (this);
		}
		
		mComboBox = null;
	}
	
	@Override
	public void actionPerformed(java.awt.event.ActionEvent e)
	{
		updatePropertyValue ();
	}
	
	@Override
	protected boolean _setParameter (String key, Object param)
	{
		return false;
	}
}
